<?php
require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../extend/phpmail/vendor/autoload.php';
//require_once __DIR__ . '/../extend/qiniu/vendor/autoload.php'; 
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//use Qiniu\Auth;
//use Qiniu\Storage\UploadManager;

// 辅助函数 :邮箱验证码
function generate_verification_code() {
    return rand(100000, 999999);
}
// 辅助函数 ：获取邮箱服务器信息
function get_mail_server_info() {
    $pdo = connect_db();
    $stmt = $pdo->query("SELECT * FROM star_mail WHERE uid = 1");
    return $stmt->fetch(PDO::FETCH_ASSOC);
}
// 发送验证码函数
function send_verification_code($mail) {
    $redis = connect_redis();
    $mail_address = $mail . '@qq.com';
    $redis_key = "verification_code:{$mail}";
    if ($redis->exists($redis_key)) {
        return json_response(500, '发送频繁，请60秒后重试');
    }
    $pdo = connect_db();
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM star_user WHERE account = :mail");
    $stmt->bindParam(':mail', $mail, PDO::PARAM_STR);
    $stmt->execute();
    if ($stmt->fetchColumn()) {
        return json_response(500, '该用户已注册，请勿重复注册');
    }
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM star_reg WHERE account = :mail");
    $stmt->bindParam(':mail', $mail, PDO::PARAM_STR);
    $stmt->execute();
    $exists = $stmt->fetchColumn();
    $code = generate_verification_code();
    $expiration_date = date('Y-m-d H:i:s', strtotime('+2 minutes'));
    try {
        if ($exists) {
            $stmt = $pdo->prepare("UPDATE star_reg SET code = :code, expiration_date = :expiration_date WHERE account = :mail");
            $stmt->bindParam(':mail', $mail, PDO::PARAM_STR);
        } else {
            $stmt = $pdo->prepare("INSERT INTO star_reg (account, mail, code, expiration_date) VALUES (:account, :mail, :code, :expiration_date)");
            $stmt->bindParam(':account', $mail, PDO::PARAM_STR);
            $stmt->bindParam(':mail', $mail_address, PDO::PARAM_STR);
        }
        $stmt->bindParam(':code', $code, PDO::PARAM_STR);
        $stmt->bindParam(':expiration_date', $expiration_date, PDO::PARAM_STR);
        $stmt->execute();
        $redis->setex($redis_key, 60, $code);
        $mail_info = get_mail_server_info();
        if (!$mail_info) {
            return json_response(500, '邮件服务器信息未配置');
        }
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = $mail_info['host'];
            $mail->SMTPAuth = true;
            $mail->Username = $mail_info['username'];
            $mail->Password = $mail_info['password'];
            $mail->SMTPSecure = $mail_info['agreement'];
            $mail->Port = $mail_info['port'];
            $mail->setFrom($mail_info['mail_address'], $mail_info['mail_user']);
            $mail->addAddress($mail_address);
            $mail->isHTML(true);
            $mail->Subject = '注册验证码';
            $mail->Body = "<!DOCTYPE html>
<html lang='zh-CN'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <style>
        body {
            font-family: 'Comic Sans MS', cursive, sans-serif;
            background-color: #F0F0F0;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 600px;
            margin: 0 auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .header {
            background-image: url('https://api.lovestory.wiki/api/mc/?username=2036513862');
            background-size: cover;
            height: 300px;
            border-top-left-radius: 10px;
            border-top-right-radius: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .header h1 {
            color: white;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
            font-size: 36px;
            margin: 0;
        }
        .content {
            padding: 20px;
        }
        .content p {
            font-size: 18px;
            line-height: 1.6;
        }
        .footer {
            background-color: #333;
            color: white;
            text-align: center;
            padding: 10px;
            border-bottom-left-radius: 10px;
            border-bottom-right-radius: 10px;
            font-size: 14px;
        }
        .button {
            display: inline-block;
            background-color: #FF6600;
            color: white;
            padding: 10px 20px;
            text-decoration: none;
            border-radius: 5px;
            font-weight: bold;
            margin-top: 15px;
        }
        .button:hover {
            background-color: #FF8800;
        }
        .highlight {
            color: red;
        }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h1>来自半曲的问候</h1>
        </div>
        <div class='content'>
            <h1>亲爱的小伙伴：</h1>
            <p>你好呀！在这个充满幻想的二次元世界里，有一份特别的消息要告诉你。</p>
            <p>这里有一场超棒的后台传送门即将开启，有免费的接口、有趣的社交环境，还有各种特别的功能等着你的发现！</p>
            <a href='https://lovestory.wiki/index.php/archives/564/' class='button'>了解更多</a>
            <p>期待在那里与你相遇，一起沉浸在二次元的欢乐海洋中！</p>
            <p>祝好！</p>
            <h3>关于传送门的验证钥匙:<span class='highlight'>{$code}</span></h3>
        </div>
        <div class='footer'>
            &copy; 2025 繁控星理-<a href='https://lovestory.wiki/index.php/archives/564/'>了解更多</a>
        </div>
    </div>
</body>
</html>";

            $mail->send();
            return json_response(200, '验证码已发送');
        } catch (Exception $e) {
            return json_response(500, '邮件发送失败: ' . $e->getMessage());
        }
    } catch (PDOException $e) {
        return json_response(500, '验证码保存失败: ' . $e->getMessage());
    }
}

// 注册函数
function register_with_code($account, $password, $username, $code) {
    $pdo = connect_db();
    $stmt = $pdo->prepare("SELECT account, mail, expiration_date FROM star_reg WHERE code = :code");
    $stmt->bindParam(':code', $code, PDO::PARAM_STR);
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$result) {
        return json_response(500, '验证码不存在');
    }

    if ($result['expiration_date'] < date('Y-m-d H:i:s')) {
        return json_response(500, '验证码已失效，请重新发送');
    }
    if ($result['account'] != $account) {
        return json_response(500, '验证码与账号不匹配');
    }
    if (!ctype_digit($account) || strlen($account) < 6 || strlen($account) > 12) {
        return json_response(500, '账号需要大于6位小于12位数并且只支持数字。建议使用QQ号注册。');
    }

    if (!preg_match('/^(?=.*[a-zA-Z])(?=.*\d).{6,12}$/', $password)) {
        return json_response(500, '密码需要大于6位小于12位并且需要数字和字母的组合。');
    }
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM star_user WHERE account = :account");
    $stmt->bindParam(':account', $account, PDO::PARAM_STR);
    $stmt->execute();
    if ($stmt->fetchColumn()) {
        return json_response(500, '该账号已被注册。');
    }
    $password = password_hash($password, PASSWORD_BCRYPT);
    $user_introduce = '这是一个默认的个人简介';
    $user_title = '小白';
    $reg_time = date('Y-m-d H:i:s');
    $vip_time = date('Y-m-d H:i:s', strtotime('+1 day'));
    $user_key = generate_user_key();
    $user_balance = '3';
    $user_ip = get_user_ip();
    $mail = $result['mail'];
    try {
        $stmt = $pdo->prepare("INSERT INTO star_user (account, password, username, user_introduce, user_title, reg_time, vip_time, user_key, user_balance, user_ip, mail) 
                               VALUES (:account, :password, :username, :user_introduce, :user_title, :reg_time, :vip_time, :user_key, :user_balance, :user_ip, :mail)");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->bindParam(':password', $password, PDO::PARAM_STR);
        $stmt->bindParam(':username', $username, PDO::PARAM_STR);
        $stmt->bindParam(':user_introduce', $user_introduce, PDO::PARAM_STR);
        $stmt->bindParam(':user_title', $user_title, PDO::PARAM_STR);
        $stmt->bindParam(':reg_time', $reg_time, PDO::PARAM_STR);
        $stmt->bindParam(':vip_time', $vip_time, PDO::PARAM_STR);
        $stmt->bindParam(':user_key', $user_key, PDO::PARAM_STR);
        $stmt->bindParam(':user_balance', $user_balance, PDO::PARAM_STR);
        $stmt->bindParam(':user_ip', $user_ip, PDO::PARAM_STR);
        $stmt->bindParam(':mail', $mail, PDO::PARAM_STR);
        $stmt->execute();
        return json_response(200, '注册成功');
    } catch (PDOException $e) {
        return json_response(500, '注册失败: ' . $e->getMessage());
    }
}

// 登录函数
function login($identifier, $password) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT * FROM star_user WHERE account = :identifier OR mail = :identifier");
        $stmt->bindParam(':identifier', $identifier, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            if (filter_var($identifier, FILTER_VALIDATE_EMAIL)) {
                return json_response(500, '该邮箱未绑定');
            } else {
                return json_response(500, '该账号不存在');
            }
        }
        if ($user['user_permissions'] == 2) {
            return json_response(500, '账号已被封禁!');
        }
        if (!password_verify($password, $user['password'])) {
            return json_response(500, '密码错误');
        }
        if ($user['vip_time'] < date('Y-m-d H:i:s')) {
            return json_response(500, '会员到期，请充值', ['user_id' => $user['uid']]);
        }
        if ($user['user_token'] > date('Y-m-d H:i:s')) {
            return json_response(200, '已登录', ['user_id' => $user['uid']]);
        }
        $user_token = date('Y-m-d H:i:s', strtotime('+3 days'));
        $stmt = $pdo->prepare("UPDATE star_user SET user_token = :user_token WHERE uid = :uid");
        $stmt->bindParam(':user_token', $user_token, PDO::PARAM_STR);
        $stmt->bindParam(':uid', $user['uid'], PDO::PARAM_INT);
        $stmt->execute();
        return json_response(200, '登录成功', [
            'user_id' => $user['uid'],
            'account' => $user['account'],
            'user_token' => $user_token
        ]);
    } catch (PDOException $e) {
        return json_response(500, '登录失败: ' . $e->getMessage());
    }
}
//退出登录函数
function offlogin($account) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT * FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return json_response(500, '账号不存在');
        }
        $currentTime = date('Y-m-d H:i:s');
        if ($user['user_token'] < $currentTime) {
            return json_response(500, '账号未登录');
        }
        $yesterday = date('Y-m-d H:i:s', strtotime('-1 day'));
        $stmt = $pdo->prepare("UPDATE star_user SET user_token = :user_token WHERE account = :account");
        $stmt->bindParam(':user_token', $yesterday, PDO::PARAM_STR);
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        
        return json_response(200, '操作成功', [
            'account' => $account,
            'user_token' => $yesterday
        ]);
    } catch (PDOException $e) {
        return json_response(500, '操作失败: ' . $e->getMessage());
    }
}
//验证都函数
function verifytoken($account) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT * FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            return json_response(500, '账号不存在');
        }
        $currentTime = date('Y-m-d H:i:s');
        if ($user['user_token'] >= $currentTime) {
            return json_response(200, '已登录', [
                'user_id' => $user['uid'],
                'account' => $user['account'],
                'user_token' => $user['user_token']
            ]);
        } else {
            return json_response(500, '账号未登录');
        }
    } catch (PDOException $e) {
        return json_response(500, '验证失败: ' . $e->getMessage());
    }
}
// 辅助函数 ：生成用户密钥
function generate_user_key() {
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $length = 16;
    $key = '';
    for ($i = 0; $i < $length; $i++) {
        $key .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $key;
}
// 辅助函数：获取用户IP
function get_user_ip() {
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}
// 辅助函数 (获取系统用户数)
function get_user_count() {
    $pdo = connect_db();
    try {
        $stmt = $pdo->query("SELECT COUNT(*) FROM star_user");
        $count = $stmt->fetchColumn();
        return json_response(200, '获取成功', ['count' => $count]);
    } catch (PDOException $e) {
        return json_response(500, '获取失败: ' . $e->getMessage());
    }
}

// 获取用户信息
function get_user_information($account) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT account, username, user_introduce, user_title, user_avatar, reg_time, vip_time, user_key, user_balance, user_ip, mail, user_token, user_permissions FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return json_response(500, '账号未注册');
        }
        if ($user['user_token'] < date('Y-m-d H:i:s')) {
            return json_response(500, '未登录');
        }
        return json_response(200, '获取成功', [
            'account' => $user['account'],
            'username' => $user['username'],
            'user_introduce' => $user['user_introduce'],
            'user_permissions' => $user['user_permissions'],
            'user_title' => $user['user_title'],
            'user_avatar' => $user['user_avatar'],
            'reg_time' => $user['reg_time'],
            'vip_time' => $user['vip_time'],
            'user_key' => $user['user_key'],
            'user_balance' => $user['user_balance'],
            'user_ip' => $user['user_ip'],
            'mail' => $user['mail']
        ]);
    } catch (PDOException $e) {
        return json_response(500, '获取失败: ' . $e->getMessage());
    }
}

// 用户修改信息函数
function modify_user_information($account, $password = null, $username = null, $user_introduce = null, $user_key = null, $mail = null, $user_avatar = null) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT * FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return json_response(500, '账号未注册');
        }
        if ($user['user_token'] < date('Y-m-d H:i:s')) {
            return json_response(500, '未登录');
        }
        if ($user_key === null) {
            $user_key = $user['user_key'];
        }
        $update_fields = [];
        $params = [
            'account' => $account,
        ];
        if ($password !== null) {
            $password = password_hash($password, PASSWORD_BCRYPT);
            $update_fields[] = 'password = :password';
            $params['password'] = $password;
        } else {
            $update_fields[] = 'password = :password';
            $params['password'] = $user['password'];
        }
        if ($username !== null) {
            $update_fields[] = 'username = :username';
            $params['username'] = $username;
        } else {
            $update_fields[] = 'username = :username';
            $params['username'] = $user['username'];
        }
        if ($user_introduce !== null) {
            $update_fields[] = 'user_introduce = :user_introduce';
            $params['user_introduce'] = $user_introduce;
        } else {
            $update_fields[] = 'user_introduce = :user_introduce';
            $params['user_introduce'] = $user['user_introduce'];
        }
        if ($user_key !== null) {
            $new_user_key = generate_user_key();
            $update_fields[] = 'user_key = :user_key';
            $params['user_key'] = $new_user_key;
        } else {
            $update_fields[] = 'user_key = :user_key';
            $params['user_key'] = $user['user_key'];
        }
        if ($mail !== null) {
            $update_fields[] = 'mail = :mail';
            $params['mail'] = $mail;
        } else {
            $update_fields[] = 'mail = :mail';
            $params['mail'] = $user['mail'];
        }
        if ($user_avatar !== null) {
            $update_fields[] = 'user_avatar = :user_avatar';
            $params['user_avatar'] = $user_avatar;
        } else {
            $update_fields[] = 'user_avatar = :user_avatar';
            $params['user_avatar'] = $user['user_avatar'];
        }
        $sql = "UPDATE star_user SET " . implode(', ', $update_fields) . " WHERE account = :account";
        $stmt = $pdo->prepare($sql);
        foreach ($params as $key => $value) {
            $stmt->bindParam(':' . $key, $value);
        }
        $stmt->execute();
        return json_response(200, '用户信息修改成功');
    } catch (PDOException $e) {
        return json_response(500, '修改失败: ' . $e->getMessage());
    }
}

// 发送找回密码验证码
function retrieve_send($account) {
    $redis = connect_redis();
    $redis_key = "retrieve_code:{$account}";
    if ($redis->exists($redis_key)) {
        return json_response(500, '发送频繁，请60秒后重试');
    }
    $pdo = connect_db();
    $stmt = $pdo->prepare("SELECT mail FROM star_user WHERE account = :account");
    $stmt->bindParam(':account', $account, PDO::PARAM_STR);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) {
        return json_response(500, '账号未注册');
    }
    $code = generate_verification_code();
    $expiration_date = date('Y-m-d H:i:s', strtotime('+2 minutes'));
    try {
        $stmt = $pdo->prepare("INSERT INTO star_reg (account, mail, code, expiration_date) VALUES (:account, :mail, :code, :expiration_date)");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->bindParam(':mail', $user['mail'], PDO::PARAM_STR);
        $stmt->bindParam(':code', $code, PDO::PARAM_STR);
        $stmt->bindParam(':expiration_date', $expiration_date, PDO::PARAM_STR);
        $stmt->execute();
        $redis->setex($redis_key, 60, $code);
        $mail_info = get_mail_server_info();
        if (!$mail_info) {
            return json_response(500, '邮件服务器信息未配置');
        }
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = $mail_info['host'];
            $mail->SMTPAuth = true;
            $mail->Username = $mail_info['username'];
            $mail->Password = $mail_info['password'];
            $mail->SMTPSecure = $mail_info['agreement'];
            $mail->Port = $mail_info['port'];
            $mail->setFrom($mail_info['mail_address'], $mail_info['mail_user']);
            $mail->addAddress($user['mail']);
            $mail->isHTML(true);
            $mail->Subject = '找回密码验证码';
$mail->Body = "<!DOCTYPE html>
<html lang='zh-CN'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #F0F0F0;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 600px;
            margin: 0 auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
       .header {
            background-image: url('https://api.lovestory.wiki/api/mc/?username=2036513862');
            background-size: cover;
            height: 300px;
            border-top-left-radius: 10px;
            border-top-right-radius: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .header h1 {
            margin: 0;
            font-size: 24px;
        }
        .content {
            padding: 20px;
        }
        .content p {
            font-size: 16px;
            line-height: 1.6;
        }
        .footer {
            background-color: #333;
            color: white;
            text-align: center;
            padding: 10px;
            border-bottom-left-radius: 10px;
            border-bottom-right-radius: 10px;
            font-size: 14px;
        }
        .highlight {
            color: red;
        }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h1>来自社区的问候</h1>
        </div>
        <div class='content'>
            <h1>亲爱的小伙伴：</h1>
            <p>很不幸的通知您...</p>
            <p>您可能在遭受密码丢失的苦恼...</p>
            <p>但是没有关系，我们很早就预测到了这种情况的发生，特地在下方为您提供了找回密码的密钥!</p>
            
            <p>祝您好运！</p>
            <h3>关于密码的验证钥匙:<span class='highlight'>{$code}</span></h3>
        </div>
        <div class='footer'>
            &copy; 2025 繁控星理-<a href='https://lovestory.wiki/index.php/archives/564/'>了解更多</a>
        </div>
    </div>
</body>
</html>";
            $mail->send();
            return json_response(200, '验证码已发送');
        } catch (Exception $e) {
            return json_response(500, '邮件发送失败: ' . $e->getMessage());
        }
    } catch (PDOException $e) {
        return json_response(500, '验证码保存失败: ' . $e->getMessage());
    }
}

// 重置密码
function retrieve_password($account, $new_password, $code) {
    $pdo = connect_db();
    $stmt = $pdo->prepare("SELECT mail, expiration_date FROM star_reg WHERE account = :account AND code = :code");
    $stmt->bindParam(':account', $account, PDO::PARAM_STR);
    $stmt->bindParam(':code', $code, PDO::PARAM_STR);
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$result) {
        return json_response(500, '验证码不存在');
    }
    if ($result['expiration_date'] < date('Y-m-d H:i:s')) {
        return json_response(500, '验证码失效');
    }
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM star_user WHERE account = :account");
    $stmt->bindParam(':account', $account, PDO::PARAM_STR);
    $stmt->execute();
    if (!$stmt->fetchColumn()) {
        return json_response(500, '账号未注册');
    }
    $new_password = password_hash($new_password, PASSWORD_BCRYPT);
    $stmt = $pdo->prepare("UPDATE star_user SET password = :password WHERE account = :account");
    $stmt->bindParam(':password', $new_password, PDO::PARAM_STR);
    $stmt->bindParam(':account', $account, PDO::PARAM_STR);
    $stmt->execute();
    return json_response(200, '密码重置成功');
}


// 用户头像上传函数
function upload_avatar($account, $file) {
    $pdo = connect_db();
    try {
        $stmt = $pdo->prepare("SELECT user_token FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return json_response(500, '账号未注册');
        }
        if ($user['user_token'] < date('Y-m-d H:i:s')) {
            return json_response(500, '未登录');
        }
        if (empty($file)) {
            return json_response(500, '请输入图片链接');
        }
        $stmt = $pdo->prepare("UPDATE star_user SET user_avatar = :user_avatar WHERE account = :account");
        $stmt->bindParam(':user_avatar', $file, PDO::PARAM_STR);
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        return json_response(200, '头像上传成功');
    } catch (PDOException $e) {
        return json_response(500, '头像上传失败: ' . $e->getMessage());
    }
}

//后台用户私聊函数
function user_chat($send_user, $receive_user, $content) {
    $pdo = connect_db();
    $redis = connect_redis();
    try {
        $stmt = $pdo->prepare("SELECT user_token, vip_time, user_permissions, username FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $send_user, PDO::PARAM_STR);
        $stmt->execute();
        $send_user_info = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($send_user_info['vip_time'] < date('Y-m-d H:i:s')) {
            return json_response(200, '会员到期，请充值');
        }
        
        if (!$send_user_info) {
            return json_response(500, '发送者账号未注册');
        }
        $current_time = time();
        $token_time = strtotime($send_user_info['user_token']);
        if ($token_time < $current_time) {
            return json_response(500, '发送者账号未登录');
        }

        if ($send_user_info['user_permissions'] == 2) {
            return json_response(500, '发送者账号已被封禁');
        }
        $stmt = $pdo->prepare("SELECT mail FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $receive_user, PDO::PARAM_STR);
        $stmt->execute();
        $receive_user_info = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$receive_user_info) {
            return json_response(500, '接收者账号不存在');
        }
        $chat_time = date('Y-m-d H:i:s');
        $stmt = $pdo->prepare("INSERT INTO star_user_chat (send_user, receive_user, chat_time, chat_information) VALUES (:send_user, :receive_user, :chat_time, :chat_information)");
        $stmt->bindParam(':send_user', $send_user, PDO::PARAM_STR);
        $stmt->bindParam(':receive_user', $receive_user, PDO::PARAM_STR);
        $stmt->bindParam(':chat_time', $chat_time, PDO::PARAM_STR);
        $stmt->bindParam(':chat_information', $content, PDO::PARAM_STR);
        $stmt->execute();
        $mail_info = get_mail_server_info();
        if (!$mail_info) {
            return json_response(500, '邮件服务器信息未配置');
        }
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = $mail_info['host'];
            $mail->SMTPAuth = true;
            $mail->Username = $mail_info['username'];
            $mail->Password = $mail_info['password'];
            $mail->SMTPSecure = $mail_info['agreement'];
            $mail->Port = $mail_info['port'];
            $mail->setFrom($mail_info['mail_address'], $mail_info['mail_user']);
            $mail->addAddress($receive_user_info['mail']);
            $mail->isHTML(true);
            $mail->Subject = '您有新的留言';
            $mail->Body = "<!DOCTYPE html>
<html lang='zh-CN'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <style>
        body {
            font-family: 'Comic Sans MS', cursive, sans-serif;
            background-color: #F0F0F0;
            margin: 0;
            padding: 0;
        }
        .container {
            width: 600px;
            margin: 0 auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .header {
            background-image: url('https://api.lovestory.wiki/api/mc/?username=2036513862');  
            background-size: cover;
            height: 300px;
            border-top-left-radius: 10px;
            border-top-right-radius: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .header h1 {
            color: white;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
            font-size: 36px;
            margin: 0;
        }
        .content {
            padding: 20px;
        }
        .content p {
            font-size: 18px;
            line-height: 1.6;
        }
        .footer {
            background-color: #333;
            color: white;
            text-align: center;
            padding: 10px;
            border-bottom-left-radius: 10px;
            border-bottom-right-radius: 10px;
            font-size: 14px;
        }
        .button {
            display: inline-block;
            background-color: #FF6600;
            color: white;
            padding: 10px 20px;
            text-decoration: none;
            border-radius: 5px;
            font-weight: bold;
            margin-top: 15px;
        }
        .button:hover {
            background-color: #FF8800;
        }
        .highlight {
            color: red;
        }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h1>{$send_user_info['username']}的问候</h1>
        </div>
        <div class='content'>
            <h1>亲爱的小伙伴：</h1>
            <h2>您有新留言，请在下方查看!</h2>
            <h3>留言内容:<span class='highlight'>{$content}</span></h3>
        </div>
        <div class='footer'>
            &copy; 2025 繁控星理-<a href='https://lovestory.wiki/index.php/archives/564/'>了解更多</a>
        </div>
    </div>
</body>
</html>";
            $mail->send();
            return json_response(200, '消息发送成功');
        } catch (Exception $e) {
            return json_response(500, '邮件发送失败: ' . $e->getMessage());
        }
    } catch (PDOException $e) {
        return json_response(500, '消息保存失败: ' . $e->getMessage());
    }
}

//签到函数
function check_in($account) {
    $pdo = connect_db();
    try {
        $current_time = date('Y-m-d H:i:s');
        $stmt = $pdo->prepare("SELECT user_balance FROM star_user WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$user) {
            return json_response(500, '账号不存在');
        }
        $stmt = $pdo->prepare("SELECT check_in FROM star_user_set WHERE uid = 1");
        $stmt->execute();
        $check_in_config = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$check_in_config) {
            return json_response(500, '未找到签到配置信息');
        }
        $stmt = $pdo->prepare("SELECT check_in_time FROM star_user_set WHERE account = :account");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $check_in_info = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$check_in_info) {
            $check_in_info = ['check_in_time' => '1970-01-01 00:00:00']; // 初始值，确保第一次签到成功
        }
        $last_check_in_time = strtotime($check_in_info['check_in_time']);
        $current_timestamp = strtotime($current_time);
        if ($current_timestamp - $last_check_in_time < 86500) {
            return json_response(500, '您今日已签到过了');
        }
        $new_balance = $user['user_balance'] + $check_in_config['check_in'];
        $stmt = $pdo->prepare("UPDATE star_user SET user_balance = :new_balance WHERE account = :account");
        $stmt->bindParam(':new_balance', $new_balance, PDO::PARAM_STR);
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->execute();
        $new_check_in_time = date('Y-m-d H:i:s', strtotime($current_time) + 86500); // 当前时间加一天
        $stmt = $pdo->prepare("
            INSERT INTO star_user_set (account, check_in_time) 
            VALUES (:account, :new_check_in_time)
            ON DUPLICATE KEY UPDATE check_in_time = :new_check_in_time
        ");
        $stmt->bindParam(':account', $account, PDO::PARAM_STR);
        $stmt->bindParam(':new_check_in_time', $new_check_in_time, PDO::PARAM_STR);
        $stmt->execute();
        return json_response(200, '签到成功');
    } catch (PDOException $e) {
        return json_response(500, '签到失败: ' . $e->getMessage());
    }
}
